<template>
  <view>
    <template
      v-if="
        allowMultiSign == 1 &&
        (reviewResult === actNodePermissionEnum().AGREE || reviewResult == actNodePermissionEnum.DISAGREE)
      "
    >
      <view class="signature__wrap">
        <view v-for="(item, index) in signs" :key="index" class="signature__item">
          <view class="signature__body">
            <image :src="item.base64" mode="widthFix"></image>
            <view v-if="item.status === 'processing'" class="sign__process">
              <view>上传签字中</view>
            </view>
            <view v-if="item.status === 'error'" class="sign__process">
              <view class="sign__error">上传失败</view>
            </view>
            <image
              v-if="item.status !== 'processing'"
              src="@/static/images/special-work/icon-remove.png"
              class="icon-remove"
              @click="deleteSignature(index)"
            ></image>
          </view>
        </view>
        <view class="signature__item">
          <view class="signature__body signature__add" @click="popupOpen()">
            <image src="@/static/images/special-work/icon-signature.png" class="icon-signature"></image>
            <text>添加签名</text>
          </view>
        </view>
      </view>
    </template>
    <uni-popup ref="popup" type="bottom" background-color="#ffffff" :mask-click="false">
      <view class="canvas-wrap" :style="{ height: windowHeight }">
        <view style="z-index: 888; height: 100%; width: 100%; position: absolute; top: 0; left: 0">
          <CuSignatureCanvas
            disableScroll
            landscape
            ref="signatureRef"
            backgroundColor="#ffffff"
            :maxLineWidth="10"
            :penSize="penSize"
            :openSmooth="openSmooth"
            :preferToDataURL="true"
          />
        </view>
        <view class="signature-text">请在此处签名</view>
        <view class="button-wrap">
          <button class="u-button u-button-default" @click="handleClear()">清空</button>
          <button class="u-button" @click="handleSave()">保存</button>
        </view>
        <view class="close-btn" @click="closeHandler">
          <uni-icons type="closeempty" size="24"></uni-icons>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import CuSignatureCanvas from '@/components/cu-signature-canavs/cu-signature-canavs.vue'
import { uploadBase64Request } from '@/api/file/upload.js'
import { staticUrl } from '@/config.js'
import { actNodePermissionEnum } from '../../../utils/constant'
import { mapState } from 'vuex'
export default {
  components: {
    CuSignatureCanvas
  },
  props: {
    value: {
      type: [String, Array],
      default: ''
    },
    allowMultiSign: {
      type: [String, Number],
      default: '0'
    },
    ticketId: {
      type: [String, Number],
      default: ''
    },
    nodeTaskId: {
      type: [String, Number],
      default: ''
    },
    reviewResult: {
      type: [String, Number],
      default: ''
    },
    autoUpload: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['systemInfo'])
  },
  created() {
    this.windowHeight = uni.getSystemInfoSync().windowHeight + 'px'
  },
  data() {
    return {
      signs: [],
      windowHeight: '',
      staticUrl,
      title: '请输入签名',
      penSize: 8,
      openSmooth: true
    }
  },
  methods: {
    actNodePermissionEnum() {
      return actNodePermissionEnum
    },
    deleteSignature(index) {
      this.signs.splice(index, 1)
      this.multipleEmit()
    },
    multipleEmit() {
      const _tempSigns = this.signs.filter((item) => item.url)
      const urls = _tempSigns.map((item) => item.url)
      console.log('urls', urls)
      this.$emit('input', urls)
    },
    closeHandler() {
      if (this.saveLoading) {
        return
      }
      this.$refs.popup.close()
      this.$emit('close')
    },
    open(nodeType) {
      // this.$refs.popup.open()
      // 允许多人签名
      if (Number(this.allowMultiSign) === 1) {
        console.log('value', this.value)
        // 未签名
        if (this.value.length <= 0) {
          this.$modal.showToast('请先签名')
          return
        }
        if (nodeType === '10' && this.value.length <= 1) {
          this.$modal.showToast('至少有两个签名')
          return
        }
        this.$emit('success', this.value)
      } else {
        this.$refs.popup.open()
      }
    },
    popupOpen() {
      this.$refs.popup.open()
    },
    handleSave() {
      if (this.saveLoading) {
        return
      }
      this.$refs.signatureRef.canvasToTempFilePath({
        success: async (res) => {
          // 是否为空画板 无签名
          if (res.isEmpty) {
            this.$modal.showToast('请先签名')
            return
          }
          // 生成图片的临时路径
          // app | H5 | 微信小程序 生成的是base64 res: {tempFilePath: base64}
          // this.$emit('success', res)
          let path = res.tempFilePath
          const multiple = Number(this.allowMultiSign) === 1
          const signObj = {
            status: this.autoUpload ? 'processing' : 'success',
            base64: res.tempFilePath,
            url: ''
          }
          this.signs.push(signObj)

          // 如果不是多选并且不是自动上传，显示loading遮罩
          if (!multiple && this.autoUpload) {
            uni.showLoading({
              title: '上传签字中',
              mask: true
            })
            this.saveLoading = true
          }

          // 多人签字必须自动默认上传
          if (this.autoUpload) {
            uploadBase64Request(res.tempFilePath)
              .then(({ data }) => {
                signObj.status = 'success'
                signObj.url = data.relativeUrl
                this.saveLoading = false
                uni.hideLoading()
                if (multiple) {
                  this.multipleEmit()
                } else {
                  this.$emit('input', data.relativeUrl)
                  this.$emit('success', data.relativeUrl)
                }
              })
              .catch(() => {
                signObj.status = 'error'
                this.saveLoading = false
                uni.hideLoading()
              })
          } else {
            if (!multiple) {
              this.$emit('input', path)
              this.$emit('success', path)
            }
          }
          this.$refs.popup.close()
        }
      })
    },
    handleClear() {
      if (this.saveLoading) {
        return
      }
      this.$refs.signatureRef.clear()
    }
  }
}
</script>

<style lang="scss" scoped>
.signature__wrap {
  display: flex;
  margin: 0 -10rpx;
  flex-wrap: wrap;

  .signature__item {
    padding: 0 10rpx;
    margin-bottom: 20rpx;
    width: 25%;
    flex-shrink: 0;
  }

  .icon-signature {
    width: 28rpx;
    height: 32rpx;
    margin-right: 10rpx;
  }

  .signature__body {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #dedede;
    background-color: #fff;
    border-radius: 10rpx;
    overflow: hidden;
    position: relative;
    .sign__process {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      z-index: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background: rgba(0, 0, 0, 0.4);
      view {
        color: #fff;
        font-size: 24rpx;
      }
      view.sign__error {
        color: #f44;
      }
    }
    .icon-remove {
      position: absolute;
      top: 0px;
      right: 0px;
      z-index: 3;
      width: 32rpx;
      height: 32rpx;
      border-bottom-left-radius: 10rpx;
    }

    &.signature__add {
      border-color: #88b4c4;
      background-color: #ebf4f8;
      color: #88b4c4;
    }
  }
}

.img-list-wrap {
  padding: 10rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  border: 1rpx solid;
  margin: 0 30rpx;
  border-radius: 5rpx;
  min-height: calc((100vw - 60px) / 2);

  .img-list {
    position: relative;
    width: calc((100vw - 60px) / 4);
    height: calc((100vw - 60px) / 4);

    .img-item {
      width: 100%;
      height: 100%;
    }

    .close-icon {
      position: absolute;
      right: 0;
      top: 0;
      border: 1rpx solid;
      border-radius: 50%;
      padding: 5rpx;
    }
  }
}

.continue-btn {
  margin: 40rpx auto 0;
  width: 600rpx;
  line-height: 98rpx;
  border-radius: 50rpx;
  font-size: 36rpx;
  text-align: center;
  border: 1rpx solid #454a5e;
}

.close-btn {
  position: absolute;
  z-index: 889;
  right: 10rpx;
  bottom: 20rpx;
  width: 80rpx;
  line-height: 80rpx;
  text-align: center;
}

.canvas-wrap {
  width: 100vw;
  position: relative;
  border-top: 1rpx solid #eee;
}
.signature-text {
  position: absolute;
  left: 50%;
  top: 50%;
  font-size: 60rpx;
  color: #ddd;
  transform: translate(-50%, -50%) rotate(90deg);
  z-index: 887;
  transition: transform 300ms;
}
.button-wrap {
  display: flex;
  position: absolute;
  bottom: 10px;
  left: 0;
  z-index: 889;
  transform: rotate(90deg) translate(-100%, 0%);
  transform-origin: bottom left;

  .u-button {
    width: 180rpx;
  }
}
</style>
